<template>
  <img class="logo" src="@/assets/logo.svg" />
  <el-menu
    mode="horizontal"
    class="table-menu"
    text-color="#000"
    background-color="#eee"
    active-text-color="#000"
    @select="TopMenuSelect"
  >
    <el-sub-menu index="file">
      <template #title>文件</template>
      <el-menu-item index="file-new">新建</el-menu-item>
      <el-menu-item index="file-open">打开</el-menu-item>
      <el-menu-item index="file-save">保存</el-menu-item>
      <el-sub-menu index="file-export">
        <template #title>导出</template>
        <el-menu-item index="file-export-excel">Excel</el-menu-item>
        <el-menu-item index="file-export-json">JSON</el-menu-item>
      </el-sub-menu>
      <el-sub-menu index="file-import">
        <template #title>导入</template>
        <el-menu-item index="file-import-excel">Excel</el-menu-item>
        <el-menu-item index="file-import-json">JSON</el-menu-item>
      </el-sub-menu>
    </el-sub-menu>
  </el-menu>
</template>

<script setup>
import { ShowPopup } from "@/stores/popup";
import { download, upload } from "@/libs/request";
import * as Table from "@/libs/table";

const popup = ShowPopup();

const TopMenuSelect = (val) => {
  switch (val) {
    case "file-new":
      Table.InitTable();
      break;
    case "file-open":
      popup.setter(true, "list");
      break;
    case "file-save":
      if (!Table.entity.templateId) {
        popup.setter(true, "save");
      } else {
        Table.SaveTable();
      }
      break;
    case "file-export-excel":
      if (Table.entity.templateId) {
        download(
          import.meta.env.VITE_APP_ENV + "/table/exportExcel",
          { templateId: Table.entity.templateId },
          Table.entity.templateName + "_" + Date.now() + ".xlsx"
        );
      } else {
        ElMessage({
          type: "error",
          message: "请在保存或者打开一个表格之后再进行导出操作！",
        });
      }
      break;
    case "file-export-json":
      break;
    case "file-import-excel":
      let body = document.querySelector("body");
      let input = document.createElement("input");
      input.type = "file";
      body.appendChild(input);

      input.addEventListener("change", (event) => {
        upload(
          import.meta.env.VITE_APP_ENV + "/table/importExcel",
          event.target.files[0],
          (json) => {
            Table.LoadTable({ templateConfig: JSON.stringify(json) });
          }
        );
        body.removeChild(input);
      });
      input.click();
      break;
    case "file-import-json":
      break;
  }
};
</script>

<style lang="scss" scoped>
.logo {
  float: left;
  width: 30px;
  height: 30px;
  margin: 5px 0px 0 10px;
}

.table-menu {
  float: left;
  width: 800px;
  height: 100%;
  border-bottom: none;

  :deep(.el-sub-menu__title) {
    padding-left: 10px;
    padding-right: 20px;
    border-bottom: none !important;

    i {
      right: 5px;
    }
  }
}
</style>
